import * as fs from 'fs'
import * as path from 'path'
import {getImageMD5Sync, removeJsonComments} from "../src/Uitls";
import {ImageEntity} from "../src/ImageEntiry";
import {img_resource_path, project_dir} from "../src/config";

export class HMModule {
    name: string
    srcPath: string
    constructor(name: string, path: string) {
        this.name = name
        this.srcPath = path
    }
    static allModules() {
        let config_path = path.resolve(project_dir, 'build-profile.json5')
        let config: {modules: HMModule[]} = JSON.parse(removeJsonComments(fs.readFileSync(config_path, 'utf-8')))
        return config.modules.map(e => new HMModule(e.name, e.srcPath))
    }
    get hasResource() {
        return fs.existsSync(path.resolve(project_dir, this.srcPath, img_resource_path))
    }
    get allImageResource() {
        let dir_path = path.resolve(project_dir, this.srcPath, img_resource_path)
        if (!fs.existsSync(dir_path)) {
            return []
        }
        let imgs = fs.readdirSync(dir_path)
        return imgs.map(e => new ImageEntity(e, path.resolve(dir_path, e)))
    }
    traverseEtsFile(handler: (e: string) => void) {
        let rootPath = path.resolve(project_dir, this.srcPath, 'src/main/ets')
        let stack = [rootPath]
        while (stack.length > 0) {
            let cur = stack.pop()!
            let files = fs.readdirSync(cur)
            for (let file of files) {
                let file_path = path.resolve(cur, file)
                if (fs.statSync(file_path).isDirectory()) {
                    stack.push(file_path)
                } else if (file.endsWith('.ets')) {
                    handler(file_path)
                }
            }
        }
    }
    handleRepeatImage() {
        let dir_path = path.resolve(project_dir, this.srcPath, img_resource_path)
        let map: Map<string, ImageEntity[]> = new Map()
        let imgs = fs.readdirSync(dir_path)
        for (let img of imgs) {
            let img_path = path.resolve(dir_path, img)
            let md5 = getImageMD5Sync(img_path)
            let entry = new ImageEntity(img, img_path)
            if (map.has(md5)) {
                map.get(md5)!.push(entry)
            } else {
                map.set(md5, [entry])
            }
        }
        let res = [...map].filter(e => e[1].length > 1).map(e => e[1].map(ee => ee.name))
        return res
    }
    handleUnusedImage() {

    }
}